/**************************************************************************************************
  Filename:       zcl_generic.c
  Revised:        $Date: 2014-10-24 16:04:46 -0700 (Fri, 24 Oct 2014) $
  Revision:       $Revision: 40796 $


  Description:    Zigbee Cluster Library - sample device application.


  Copyright 2006-2014 Texas Instruments Incorporated. All rights reserved.

  IMPORTANT: Your use of this Software is limited to those specific rights
  granted under the terms of a software license agreement between the user
  who downloaded the software, his/her employer (which must be your employer)
  and Texas Instruments Incorporated (the "License").  You may not use this
  Software unless you agree to abide by the terms of the License. The License
  limits your use, and you acknowledge, that the Software may not be modified,
  copied or distributed unless embedded on a Texas Instruments microcontroller
  or used solely and exclusively in conjunction with a Texas Instruments radio
  frequency transceiver, which is integrated into your product.  Other than for
  the foregoing purpose, you may not use, reproduce, copy, prepare derivative
  works of, modify, distribute, perform, display or sell this Software and/or
  its documentation for any purpose.

  YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
  PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
  INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
  NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
  TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
  NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
  LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
  INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
  OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
  OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
  (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.

  Should you have any questions regarding your right to use this Software,
  contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/

/*********************************************************************
  This application is a template to get started writing an application
  from scratch.

  Look for the sections marked with "GENERICAPP_TODO" to add application
  specific code.

  Note: if you would like your application to support automatic attribute
  reporting, include the BDB_REPORTING compile flag.
*********************************************************************/

/*********************************************************************
 * INCLUDES
 */
#include "ZComDef.h"
#include "OSAL.h"
#include "AF.h"
#include "ZDApp.h"
#include "ZDObject.h"
#include "MT_SYS.h"

#include "nwk_util.h"

#include "zcl.h"
#include "zcl_general.h"
#include "zcl_ha.h"
#include "zcl_diagnostic.h"
#include "zcl_generic.h"

#include "bdb.h"
#include "bdb_interface.h"
#include "gp_interface.h"

#include "mfg.h"

#include "cmd_uart.h"
#include "cmd_cfg.h"
#include "cmd_nwk.h"
#include "cmd_zcl.h"

#include "mfg_coord.h"

#if defined ( INTER_PAN )
#if defined ( BDB_TL_INITIATOR )
  #include "bdb_touchlink_initiator.h"
#endif // BDB_TL_INITIATOR
#if defined ( BDB_TL_TARGET )
  #include "bdb_touchlink_target.h"
#endif // BDB_TL_TARGET
#endif // INTER_PAN

#if defined ( BDB_TL_INITIATOR ) || defined ( BDB_TL_TARGET )
  #include "bdb_touchlink.h"
#endif

#include "OnBoard.h"

/*
#include "mfg.h"
#include "util/mfg_Stack.h"
#include "util/mfg_coord.h"
#include "cmd/cmd.h"
#include "cmd/cmd_pkt.h"
#include "cmd/cmd_cfg.h"
#include "cmd/cmd_nwk.h"
#include "cmd/cmd_zcl.h"
*/

/*********************************************************************
 * MACROS
 */


/*********************************************************************
 * CONSTANTS
 */


/*********************************************************************
 * TYPEDEFS
 */

/*********************************************************************
 * GLOBAL VARIABLES
 */
byte Generic_TaskID;


/*********************************************************************
 * GLOBAL FUNCTIONS
 */
 
/*********************************************************************
 * LOCAL VARIABLES
 */

uint8 giGenAppScreenMode = GENERIC_MAINMODE;   // display the main screen mode first

uint8 gPermitDuration = 0;    // permit joining default to disabled

devStates_t Generic_NwkState = DEV_INIT;


/*********************************************************************
 * LOCAL FUNCTIONS
 */
static void Generic_BasicResetCB( void );
static void Generic_ProcessCommissioningStatus(bdbCommissioningModeMsg_t *bdbCommissioningModeMsg);

// app display functions

// Functions to process ZCL Foundation incoming Command/Response messages
static void Generic_ProcessIncomingMsg( zclIncomingMsg_t *msg );

/*********************************************************************
 * STATUS STRINGS
 */

/*********************************************************************
 * ZCL General Profile Callback table
 */
static zclGeneral_AppCallbacks_t Generic_CmdCallbacks =
{
  Generic_BasicResetCB,             // Basic Cluster Reset command
  NULL,                                   // Identify Trigger Effect command
  NULL,
  NULL,
#ifdef ZCL_ON_OFF
  NULL,                                   // On/Off cluster commands
  NULL,                                   // On/Off cluster enhanced command Off with Effect
  NULL,                                   // On/Off cluster enhanced command On with Recall Global Scene
  NULL,                                   // On/Off cluster enhanced command On with Timed Off
#endif
#ifdef ZCL_LEVEL_CTRL
  NULL,                                   // Level Control Move to Level command
  NULL,                                   // Level Control Move command
  NULL,                                   // Level Control Step command
  NULL,                                   // Level Control Stop command
#endif
#ifdef ZCL_GROUPS
  NULL,                                   // Group Response commands
#endif
#ifdef ZCL_SCENES
  NULL,                                  // Scene Store Request command
  NULL,                                  // Scene Recall Request command
  NULL,                                  // Scene Response command
#endif
#ifdef ZCL_ALARMS
  NULL,                                  // Alarm (Response) commands
#endif
#ifdef SE_UK_EXT
  NULL,                                  // Get Event Log command
  NULL,                                  // Publish Event Log command
#endif
  NULL,                                  // RSSI Location command
  NULL                                   // RSSI Location Response command
};

/*********************************************************************
 * GENERICAPP_TODO: Add other callback structures for any additional application specific 
 *       Clusters being used, see available callback structures below.
 *
 *       bdbTL_AppCallbacks_t 
 *       zclApplianceControl_AppCallbacks_t 
 *       zclApplianceEventsAlerts_AppCallbacks_t 
 *       zclApplianceStatistics_AppCallbacks_t 
 *       zclElectricalMeasurement_AppCallbacks_t 
 *       zclGeneral_AppCallbacks_t 
 *       zclGp_AppCallbacks_t 
 *       zclHVAC_AppCallbacks_t 
 *       zclLighting_AppCallbacks_t 
 *       zclMS_AppCallbacks_t 
 *       zclPollControl_AppCallbacks_t 
 *       zclPowerProfile_AppCallbacks_t 
 *       zclSS_AppCallbacks_t  
 *
 */

/*********************************************************************
 * @fn          Generic_Init
 *
 * @brief       Initialization function for the zclGeneral layer.
 *
 * @param       none
 *
 * @return      none
 */
void Generic_Init( byte task_id )
{
  Generic_TaskID = task_id;
  cmd_uartInit( task_id );
  osal_set_event( Generic_TaskID, MFG_INIT_EVENT );
  osal_start_reload_timer( Generic_TaskID, MFG_PERIOD_EVENT, 1000 );
  MFG_RandomExtPanid();
  MFG_InitCallback(task_id);

  // This app is part of the Home Automation Profile
  bdb_RegisterSimpleDescriptor( &Generic_SimpleDesc );
  cmdZcl_InitSrcEP( &Generic_SimpleDesc );

  // Register the ZCL General Cluster Library callback functions
  zclGeneral_RegisterCmdCallbacks( GENERICAPP_ENDPOINT, &Generic_CmdCallbacks );
  
  // GENERICAPP_TODO: Register other cluster command callbacks here

  // Register the application's attribute list
  zcl_registerAttrList( GENERICAPP_ENDPOINT, Generic_NumAttributes, Generic_Attrs );

  // Register the Application to receive the unprocessed Foundation command/response messages
  zcl_registerForMsg( Generic_TaskID );

#ifdef ZCL_DISCOVER
  // Register the application's command list
  zcl_registerCmdList( GENERICAPP_ENDPOINT, zclCmdsArraySize, Generic_Cmds );
#endif
  // Register for all key events - This app will handle all key events
  RegisterForKeys( Generic_TaskID );

  bdb_RegisterCommissioningStatusCB( Generic_ProcessCommissioningStatus );
}

/*********************************************************************
 * @fn          zclSample_event_loop
 *
 * @brief       Event Loop Processor for zclGeneral.
 *
 * @param       none
 *
 * @return      none
 */
uint16 Generic_event_loop( uint8 task_id, uint16 events )
{
  afIncomingMSGPacket_t *MSGpkt;

  (void)task_id;  // Intentionally unreferenced parameter

  if ( events & SYS_EVENT_MSG )
  {
    while ( (MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( Generic_TaskID )) )
    {
      switch ( MSGpkt->hdr.event )
      {
        case ZDO_CB_MSG:
          MFG_processZDOMgs( (zdoIncomingMsg_t *)MSGpkt );
          break;

        case ZCL_INCOMING_MSG:
          // Incoming ZCL Foundation command/response messages
          Generic_ProcessIncomingMsg( (zclIncomingMsg_t *)MSGpkt );
          break;
          
        case AF_DATA_CONFIRM_CMD:
          {
            afDataConfirm_t* afDataCnf = (afDataConfirm_t *)MSGpkt;
            if( afDataCnf->afCnfCB )
            {
              afDataCnf->afCnfCB( afDataCnf->hdr.status, afDataCnf->endpoint, afDataCnf->transID, afDataCnf->cnfParam );
            }
          }
          break;
          
        case SPI_INCOMING_ZAPP_DATA:
          {
            cmd_uartRxMsg_t* uartMsg = (cmd_uartRxMsg_t*)MSGpkt;
            cmd_uartRxProcess( uartMsg->size, uartMsg->data );
          }
          break;

        case KEY_CHANGE:
          //Generic_HandleKeys( ((keyChange_t *)MSGpkt)->state, ((keyChange_t *)MSGpkt)->keys );
          break;

        case ZDO_STATE_CHANGE:
          Generic_NwkState = (devStates_t)(MSGpkt->hdr.status);

          // now on the network
          if ( (Generic_NwkState == DEV_ZB_COORD) ||
               (Generic_NwkState == DEV_ROUTER)   ||
               (Generic_NwkState == DEV_END_DEVICE) )
          {

          }
          break;

        default:
          break;
      }

      // Release the memory
      osal_msg_deallocate( (uint8 *)MSGpkt );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }
  /* GENERICAPP_TODO: handle app events here */
  
  if ( events & CMD_EVT_RX_TIMEOUT )
  {
    cmd_uartRxTimeout();
    return ( events ^ CMD_EVT_RX_TIMEOUT );
  }

  if ( events & CMD_EVT_TX_TRIGGER )
  {
    cmd_UartTxTrigger();
    return ( events ^ CMD_EVT_TX_TRIGGER );
  }
  
  if ( events & MFG_INIT_EVENT )
  {
    cmdCfg_Boot( 0, Generic_AppVersion );
    return ( events ^ MFG_INIT_EVENT );
  }
  
  if( events & MFG_PERIOD_EVENT )
  {
    MFG_PeriodCallback();
    return ( events ^ MFG_PERIOD_EVENT );
  }
  
  // Discard unknown events
  return 0;
}

ZStatus_t MFG_ZclPluginCallback( zclIncoming_t *pInMsg )
{
  //extern SimpleDescriptionFormat_t Generic_SimpleDesc;
  endPointDesc_t* epDesc = afFindEndPointDesc( pInMsg->msg->endPoint );
  
  if( epDesc != NULL )
  {
    SimpleDescriptionFormat_t *simpleDesc = epDesc->simpleDesc;
    if( zcl_ClientCmd( pInMsg->hdr.fc.direction ) )
    {
      return CmdZcl_ZclPluginCallback( pInMsg );
    }
    else
    {
      if ( MFG_MatchSeverCmd(pInMsg->msg->clusterId, pInMsg->hdr.commandID) )
      {
        return CmdZcl_ZclPluginCallback( pInMsg );
      }
      else
      {
        uint8  num = simpleDesc->AppNumInClusters;
        cId_t    *pCluster = simpleDesc->pAppInClusterList;
        uint8 n;
        for(n=0; n<num; n++)
        {
          if(pInMsg->msg->clusterId == pCluster[n])
          {
            return CmdZcl_ZclPluginCallback( pInMsg );
          }
        }
      }
    }
  }
  return ZFailure;
}

/*********************************************************************
 * @fn      Generic_ProcessCommissioningStatus
 *
 * @brief   Callback in which the status of the commissioning process are reported
 *
 * @param   bdbCommissioningModeMsg - Context message of the status of a commissioning process
 *
 * @return  none
 */
static void Generic_ProcessCommissioningStatus(bdbCommissioningModeMsg_t *bdbCommissioningModeMsg)
{
  if(bdbCommissioningModeMsg->bdbCommissioningStatus == BDB_COMMISSIONING_IN_PROGRESS)
  {
    return;
  }
  switch(bdbCommissioningModeMsg->bdbCommissioningMode)
  {
    case BDB_COMMISSIONING_FORMATION:
      if(bdbCommissioningModeMsg->bdbCommissioningStatus == BDB_COMMISSIONING_SUCCESS)
      {
        bdb_StartCommissioning( BDB_COMMISSIONING_MODE_NWK_STEERING );
      }
    break;

    case BDB_COMMISSIONING_NWK_STEERING:
      if(bdbCommissioningModeMsg->bdbCommissioningStatus == BDB_COMMISSIONING_SUCCESS)
      {
        cmdCfg_CoordStartNotify( COORD_STA_NET, _NIB.nwkLogicalChannel, _NIB.nwkPanId, NLME_GetExtAddr( ) );
      }
    break;

    case BDB_COMMISSIONING_FINDING_BINDING:

    break;

    case BDB_COMMISSIONING_INITIALIZATION:
      {
        uint8 sta = COORD_STA_IDLE;
        if(bdbCommissioningModeMsg->bdbCommissioningStatus == BDB_COMMISSIONING_NETWORK_RESTORED)
        {
          sta = COORD_STA_NET;
        }
        cmdCfg_CoordStartNotify( sta, _NIB.nwkLogicalChannel, _NIB.nwkPanId, NLME_GetExtAddr( ) );
      }
    break;
  }
}

/*********************************************************************
 * @fn      Generic_ProcessTouchlinkTargetEnable
 *
 * @brief   Called to process when the touchlink target functionality
 *          is enabled or disabled
 *
 * @param   none
 *
 * @return  none
 */
#if ( defined ( BDB_TL_TARGET ) && (BDB_TOUCHLINK_CAPABILITY_ENABLED == TRUE) )
static void Generic_ProcessTouchlinkTargetEnable( uint8 enable )
{
  if ( enable )
  {
    HalLedSet ( HAL_LED_1, HAL_LED_MODE_ON );
  }
  else
  {
    HalLedSet ( HAL_LED_1, HAL_LED_MODE_OFF );
  }
}
#endif

/*********************************************************************
 * @fn      Generic_BasicResetCB
 *
 * @brief   Callback from the ZCL General Cluster Library
 *          to set all the Basic Cluster attributes to default values.
 *
 * @param   none
 *
 * @return  none
 */
static void Generic_BasicResetCB( void )
{

  /* GENERICAPP_TODO: remember to update this function with any
     application-specific cluster attribute variables */
  Generic_ResetAttributesToDefaultValues();
}



/******************************************************************************
 *
 *  Functions for processing ZCL Foundation incoming Command/Response messages
 *
 *****************************************************************************/

/*********************************************************************
 * @fn      Generic_ProcessIncomingMsg
 *
 * @brief   Process ZCL Foundation incoming message
 *
 * @param   pInMsg - pointer to the received message
 *
 * @return  none
 */
static void Generic_ProcessIncomingMsg( zclIncomingMsg_t *pInMsg )
{
  CmdZcl_ProcessIncomingMsg( pInMsg );
  if ( pInMsg->attrCmd )
    osal_mem_free( pInMsg->attrCmd );
}

/****************************************************************************
****************************************************************************/


